//
//  ScanViewController.m
//  LiangYa_BObject
//
//  Created by dllo on 15/11/3.
//  Copyright © 2015年 YuHao. All rights reserved.
//

#import "ScanViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "ZXingObjC/ZXingObjC.h"
#import "WebViewController.h"

@interface ScanViewController ()<AVCaptureMetadataOutputObjectsDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic, strong) UIView *viewPreview;
@property (strong, nonatomic) UIView *boxView;
@property (nonatomic, assign) BOOL isReading;
@property (strong, nonatomic) CALayer *scanLayer;
@property (nonatomic, strong) AVCaptureSession *captureSession;
@property (strong, nonatomic) UIImagePickerController *imagePiacker;
@property (nonatomic, strong)  UIImageView *imageView;


@property (nonatomic, strong) UIButton *backB;

@end

@implementation ScanViewController

- (void)viewWillAppear:(BOOL)animated
{
     [self startReading];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.viewPreview = [[UIView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:_viewPreview];
    
    self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 100, ScreenWidth - 100, ScreenWidth - 100)];
    [self.view addSubview:_imageView];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 330, ScreenWidth, ScreenWidth - 100)];
    label.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:label];
    label.textColor = [UIColor whiteColor];
    label.text = @"将二维码/条形码放入框内,即可自动扫描";
    
    // 返回按钮
    self.backB = [UIButton buttonWithType:UIButtonTypeSystem];
    _backB.backgroundColor = [UIColor colorWithRed:1.000 green:0.000 blue:0.139 alpha:1.000];
    _backB.frame = CGRectMake(20, 20, 40, 40);
    _backB.layer.cornerRadius = 20;
    UIImage *backI = [[UIImage imageNamed:@"picture1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [_backB setImage:backI forState:UIControlStateNormal];
    [_backB setImageEdgeInsets:UIEdgeInsetsMake(5, 5, 5, 5)];
    [_backB addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_backB];
    
    
    
    UIButton *photo = [UIButton buttonWithType:UIButtonTypeSystem];
    photo.frame = CGRectMake(ScreenWidth - 60, 25, 50, 30);
    [photo setTitle:@"相册" forState:UIControlStateNormal];
    photo.backgroundColor = [UIColor redColor];
    photo.layer.cornerRadius = 10;
    [self.view addSubview:photo];
    [photo addTarget:self action:@selector(photoClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
       // Do any additional setup after loading the view.
}

// uiPickerIamgeController访问相册
- (void)photoClick:(UIButton *)btn
{
    self.imagePiacker = [[UIImagePickerController alloc]init];
    // 设置类型 图片列表 摄像头  相机相册
    _imagePiacker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    self.imagePiacker.delegate = self;
    _imagePiacker.allowsEditing = YES;
    _imagePiacker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:_imagePiacker animated:YES completion:^{
        
    }];
}

// UIImagePickerController 协议方法

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    [self dismissViewControllerAnimated:YES completion:^{
        self.imageView.image = image;
        [self getInfoWithImage:self.imageView.image];
    }];
    [self.imagePiacker removeFromParentViewController];
}

- (void)getInfoWithImage:(UIImage *)img{
    
    UIImage *loadImage = img;
    CGImageRef image = loadImage.CGImage;
    // 本地扫描的图片
    ZXLuminanceSource *source = [[ZXCGImageLuminanceSource alloc]initWithCGImage:image];
    //位图
    ZXBinaryBitmap *bitMap = [ZXBinaryBitmap binaryBitmapWithBinarizer:[ZXHybridBinarizer binarizerWithSource:source]];
    ZXDecodeHints *hit = [ZXDecodeHints hints];
    // 进入类库 可以解码所有条码类型
    ZXMultiFormatReader *read = [ZXMultiFormatReader reader];
    ZXResult *result = [read decode:bitMap hints:hit error:nil];
    if (result) {
        
        [self showInfoWithmessage:result.text];
        

//        WebViewController *web = [[WebViewController alloc] init];
//        web.str1 = result.text;
//        [self presentViewController:web animated:YES completion:^{
//        
//        }];
    }
    else{
        [self showInfoWithmessage:@"解析失败"];
    }
}

- (void)showInfoWithmessage:(NSString *)message
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:1];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
        
    }];
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}

- (void)setStop:(UIButton *)btn
{
    [_captureSession stopRunning];
    _captureSession = nil;
    [_scanLayer removeFromSuperlayer];
}

- (BOOL)startReading
{
    // 初始化捕捉设备
    AVCaptureDevice *capture = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    // 用captureDevice创建输入流
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:capture error:nil];
    
    if (!input && self.imageView.image == nil) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"无输入" preferredStyle:1];
        UIAlertAction *okaction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
            
        }];
        [alert addAction:okaction];
        [self presentViewController:alert  animated:YES completion:^{
            
        }];
        return NO;
    }
    if (self.imageView.image != nil) {
        
        [self getInfoWithImage:self.imageView.image];
        return NO;
    }
    
    //创建媒体数据输出流
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    //实例化捕捉会话
    self.captureSession = [[AVCaptureSession alloc] init];
    [_captureSession setSessionPreset:AVCaptureSessionPresetHigh];
    //将输入流添加到会话
    
    [_captureSession addInput:input];
    //将媒体输出流添加到会话中
    [_captureSession addOutput:captureMetadataOutput];
    
    //设置代理
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    //设置输出媒体数据类型
    [captureMetadataOutput setMetadataObjectTypes:@[AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeQRCode]];
    //实例化预览图层
    AVCaptureVideoPreviewLayer *videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    //设置预览图层填充方式
    [videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    //设置图层的frame
    [videoPreviewLayer setFrame:_viewPreview.layer.bounds];
    //将图层添加到预览view的图层上
    [_viewPreview.layer addSublayer:videoPreviewLayer];
    //设置扫描范围
    //    x y 互换  width height 互换
    captureMetadataOutput.rectOfInterest = CGRectMake(0.2,0.2,0.8,0.8);
    //扫描框
//    self.boxView = [[UIView alloc] initWithFrame:CGRectMake(_viewPreview.bounds.size.width * 0.15f, _viewPreview.bounds.size.height * 0.15f, _viewPreview.bounds.size.width - _viewPreview.bounds.size.width * 0.3f, _viewPreview.bounds.size.height - _viewPreview.bounds.size.height * 0.3f)];
    self.boxView = [[UIView alloc] initWithFrame:CGRectMake(50, 100, ScreenWidth - 100, ScreenWidth - 100)];
    _boxView.layer.borderColor = [UIColor greenColor].CGColor;
    _boxView.layer.borderWidth = 1.0f;
    [_viewPreview addSubview:_boxView];
    
    //扫描线
    self.scanLayer = [[CALayer alloc] init];
    _scanLayer.frame = CGRectMake(3, 0, _boxView.bounds.size.width-6, 1);
    _scanLayer.backgroundColor = [UIColor greenColor].CGColor;
    [_boxView.layer addSublayer:_scanLayer];
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.2f target:self selector:@selector(moveScanLayer:) userInfo:nil repeats:YES];
    [timer fire];
    
    //10.开始扫描
    [_captureSession startRunning];
    return YES;
    
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    //判断是否有数据
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        
        
        //判断回传的数据类型
        if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode] || [[metadataObj type] isEqualToString:AVMetadataObjectTypeEAN13Code] || [[metadataObj type] isEqualToString:AVMetadataObjectTypeEAN8Code] || [[metadataObj type] isEqualToString:AVMetadataObjectTypeCode128Code]) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:metadataObj.stringValue preferredStyle:1];
            
            
//
//            WebViewController *web = [[WebViewController alloc] init];
//            web.str1 = metadataObj.stringValue;
//            
//            [self presentViewController:web animated:YES completion:^{
//                
//            }];
            
            
            
            UIAlertAction *okaction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
                [_captureSession stopRunning];
                _captureSession = nil;
                [_scanLayer removeFromSuperlayer];
            }];
            [alert addAction:okaction];
            [self presentViewController:alert  animated:YES completion:^{
                
            }];
        }
    }
}

- (void)moveScanLayer:(NSTimer *)timer
{
    CGRect frame = _scanLayer.frame;
    if (_boxView.frame.size.height <= _scanLayer.frame.origin.y ) {
        self.scanLayer.hidden = YES;
        frame.origin.y = 0;
        _scanLayer.frame = frame;
    }else{
        self.scanLayer.hidden = NO;
        frame.origin.y += 5;
        [UIView animateWithDuration:0.1 animations:^{
            _scanLayer.frame = frame;
        }];
    }
}



- (void)backAction:(UIButton *)btn
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
